<template>
  <div class="tag-manager">
    <!-- 头部区域 -->
    <div class="header">
      <div class="title-group">
        <el-icon class="title-icon"><PriceTag /></el-icon>
        <h1 class="title">标签系统</h1>
      </div>
      
      <div class="action-group">
        <el-button 
          class="action-btn"
          type="primary" 
          @click="handleCreate"
        >
          <el-icon><CirclePlus /></el-icon>
          新建标签
        </el-button>
      </div>
    </div>

    <!-- 搜索与过滤 -->
    <div class="filter-bar">
      <el-input
        v-model="searchText"
        placeholder="搜索标签名称..."
        class="search-input"
        clearable
      >
        <template #prefix>
          <el-icon class="search-icon"><Search /></el-icon>
        </template>
      </el-input>
      
      <div class="color-filters">
        <div 
          v-for="color in colorPresets"
          :key="color"
          class="color-chip"
          :class="{ active: activeColor === color }"
          :style="{ backgroundColor: color }"
          @click="toggleColorFilter(color)"
        >
          <el-icon v-if="activeColor === color"><Check /></el-icon>
        </div>
      </div>
    </div>

    <!-- 标签列表 -->
    <div class="tag-grid">
      <div 
        v-for="tag in filteredTags"
        :key="tag.id"
        class="tag-card"
        :style="{ borderLeftColor: tag.color }"
      >
        <div class="tag-header">
          <el-tag 
            class="tag-display"
            :color="tag.color"
            effect="dark"
          >
            {{ tag.name }}
          </el-tag>
          <div class="tag-actions">
            <el-button 
              type="primary" 
              circle 
              plain
              @click="handleEdit(tag)"
            >
              <el-icon><Edit /></el-icon>
            </el-button>
            <el-button 
              type="danger" 
              circle 
              plain
              @click="handleDelete(tag)"
            >
              <el-icon><Delete /></el-icon>
            </el-button>
          </div>
        </div>
        
        <div class="tag-meta">
          <div class="meta-item">
            <el-icon><Clock /></el-icon>
            <span>{{ tag.createTime }}</span>
          </div>
          <div class="meta-item">
            <el-icon><PriceTag /></el-icon>
            <span>使用次数: {{ tag.usageCount }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 空状态 -->
    <div v-if="!filteredTags.length" class="empty-state">
      <el-empty description="暂无标签数据" />
      <el-button type="primary" @click="handleCreate">立即创建</el-button>
    </div>

    <!-- 创建/编辑弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEditing ? '编辑标签' : '新建标签'"
      class="tag-dialog"
      width="480px"
    >
      <el-form 
        label-position="top"
        :model="formData"
        :rules="formRules"
        ref="formRef"
      >
        <el-form-item label="标签名称" prop="name">
          <el-input 
            v-model="formData.name" 
            placeholder="输入标签名称"
            clearable
          />
        </el-form-item>
        
        <el-form-item label="标签颜色" prop="color">
          <div class="color-picker-wrapper">
            <el-color-picker
              v-model="formData.color"
              show-alpha
              :predefine="colorPresets"
            />
            <div 
              class="color-preview"
              :style="{ backgroundColor: formData.color }"
            >
              {{ formData.name || '标签预览' }}
            </div>
          </div>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="submitForm"
          :loading="submitting"
        >
          确认
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance } from 'element-plus'
import { 
  Edit, 
  Delete, 
  Search, 
  Plus, 
  CirclePlus, 
  PriceTag, 
  Clock, 
  Check 
} from '@element-plus/icons-vue'

// 类型定义
interface Tag {
  id: number
  name: string
  color: string
  createTime: string
  usageCount: number
}

// 响应式数据
const tags = ref<Tag[]>([
  { id: 1, name: '重要', color: '#ff4757', createTime: '2023-08-01', usageCount: 24 },
  { id: 2, name: '紧急', color: '#ff6b81', createTime: '2023-08-02', usageCount: 18 },
  { id: 3, name: '工作', color: '#5352ed', createTime: '2023-08-03', usageCount: 32 },
  { id: 4, name: '个人', color: '#2ed573', createTime: '2023-08-04', usageCount: 15 }
])

const searchText = ref('')
const activeColor = ref('')
const dialogVisible = ref(false)
const isEditing = ref(false)
const submitting = ref(false)
const formRef = ref<FormInstance>()

// 表单数据
const formData = reactive({
  id: 0,
  name: '',
  color: '#5352ed'
})

// 预定义颜色
const colorPresets = [
  '#ff4757', '#ff6b81', '#a4b0be', '#5352ed',
  '#2ed573', '#1e90ff', '#ffa502', '#ff6348'
]

// 计算属性
const filteredTags = computed(() => {
  return tags.value.filter(tag => {
    const matchesSearch = tag.name.toLowerCase().includes(searchText.value.toLowerCase())
    const matchesColor = !activeColor.value || tag.color === activeColor.value
    return matchesSearch && matchesColor
  })
})

// 方法
const handleCreate = () => {
  isEditing.value = false
  formData.id = 0
  formData.name = ''
  formData.color = '#5352ed'
  dialogVisible.value = true
}

const handleEdit = (tag: Tag) => {
  isEditing.value = true
  Object.assign(formData, tag)
  dialogVisible.value = true
}

const handleDelete = (tag: Tag) => {
  ElMessageBox.confirm(`确定删除标签 "${tag.name}" 吗？`, '警告', {
    confirmButtonText: '确认删除',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    tags.value = tags.value.filter(t => t.id !== tag.id)
    ElMessage.success('删除成功')
  })
}

const toggleColorFilter = (color: string) => {
  activeColor.value = activeColor.value === color ? '' : color
}

const submitForm = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitting.value = true
    
    // 模拟API请求
    await new Promise(resolve => setTimeout(resolve, 800))
    
    if (isEditing.value) {
      const index = tags.value.findIndex(t => t.id === formData.id)
      tags.value.splice(index, 1, { ...formData })
    } else {
      tags.value.push({
        ...formData,
        id: Date.now(),
        createTime: new Date().toISOString().split('T')[0],
        usageCount: 0
      })
    }
    
    ElMessage.success(isEditing.value ? '修改成功' : '创建成功')
    dialogVisible.value = false
  } finally {
    submitting.value = false
  }
}

// 表单验证规则
const formRules = reactive({
  name: [
    { required: true, message: '请输入标签名称', trigger: 'blur' },
    { min: 2, max: 12, message: '长度在2到12个字符', trigger: 'blur' }
  ],
  color: [{ required: true, message: '请选择颜色', trigger: 'change' }]
})
</script>

<style scoped lang="less">
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&display=swap');

.tag-manager {
  padding: 32px;
  font-family: 'Inter', -apple-system, sans-serif;
  background: #f8f9fa;
  min-height: 100vh;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 32px;
  
  .title-group {
    display: flex;
    align-items: center;
    gap: 12px;
    
    .title {
      margin: 0;
      font-size: 28px;
      font-weight: 600;
      color: #2d3436;
    }
    
    .title-icon {
      font-size: 28px;
      color: #6c5ce7;
    }
    
    .version-tag {
      margin-left: 8px;
      background: #f1f3f5;
      color: #868e96;
    }
  }
}

.filter-bar {
  display: flex;
  gap: 24px;
  margin-bottom: 32px;
  
  .search-input {
    width: 320px;
    
    :deep(.el-input__wrapper) {
      border-radius: 8px;
      box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
    }
  }
  
  .color-filters {
    display: flex;
    gap: 8px;
    align-items: center;
    
    .color-chip {
      width: 32px;
      height: 32px;
      border-radius: 6px;
      cursor: pointer;
      display: flex;
      align-items: center;
      justify-content: center;
      color: white;
      transition: all 0.2s ease;
      
      &:hover {
        transform: scale(1.1);
      }
      
      &.active {
        box-shadow: 0 0 0 3px rgba(255, 255, 255, 0.8), 
                   0 0 0 6px var(--el-color-primary);
      }
    }
  }
}

.tag-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 24px;
}

.tag-card {
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  border-left: 4px solid transparent;
  transition: all 0.2s ease;
  
  &:hover {
    transform: translateY(-4px);
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
  }
  
  .tag-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    
    .tag-display {
      font-size: 16px;
      font-weight: 500;
      padding: 8px 16px;
      border-radius: 20px;
    }
    
    .tag-actions {
      display: flex;
      gap: 8px;
      opacity: 0;
      transition: opacity 0.2s ease;
    }
  }
  
  &:hover .tag-actions {
    opacity: 1;
  }
  
  .tag-meta {
    display: flex;
    flex-direction: column;
    gap: 8px;
    font-size: 14px;
    color: #868e96;
    
    .meta-item {
      display: flex;
      align-items: center;
      gap: 8px;
    }
  }
}

.empty-state {
  text-align: center;
  padding: 48px 0;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.color-picker-wrapper {
  display: flex;
  align-items: center;
  gap: 16px;
  
  .color-preview {
    flex: 1;
    padding: 12px;
    border-radius: 8px;
    text-align: center;
    color: white;
    font-weight: 500;
    text-shadow: 0 1px 2px rgba(0, 0, 0, 0.2);
  }
}

.tag-dialog {
  :deep(.el-dialog__body) {
    padding: 24px;
  }
}
</style>